package cn.tjad.tjad2.module.document.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;

import com.hjy.http.download.DownloadManager;
import com.hjy.http.download.FileDownloadInfo;
import com.hjy.http.upload.FileUploadInfo;
import com.qiandian.android.base.common.bean.BaseBean;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.utils.UrlUtils;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.FilePicker;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.module.document.widget.DocumentFiledSelectWidget;
import cn.tjad.tjad2.module.document.widget.DocumentOperatorPanel;
import cn.tjad.tjad2.module.document.adapter.FileListAdapter;
import cn.tjad.tjad2.module.document.widget.FileSortDialog;
import cn.tjad.tjad2.module.main.activity.MainActivity;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.consts.TjadConsts;
import cn.tjad.tjad2.consts.UrlConsts;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.data.event.FileCheckedChangeEvent;
import cn.tjad.tjad2.data.event.ProjectChangedEvent;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.listener.OnItemLongClickListener;
import cn.tjad.tjad2.net.TjadHttpServer;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.DocumentHelper;
import cn.tjad.tjad2.utils.FileHandler;
import cn.tjad.tjad2.utils.FileHelper;
import cn.tjad.tjad2.utils.FileOpenUtils;
import cn.tjad.tjad2.utils.FileSort;
import cn.tjad.tjad2.utils.NetworkUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.utils.ZipUtils;
import cn.tjad.tjad2.module.common.widget.TJPopupWindow;
import cn.tjad.tjad2.module.common.dialog.CreateFolderDialog;
import cn.tjad.tjad2.module.common.dialog.FileRenameDialog;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;
import cn.tjad.tjad2.module.common.pictureselect.ImagePreviewWindow;
import cn.tjad.tjad2.module.share.OuterShareWidget;
import io.reactivex.Observable;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

public class DocumentFragment extends BaseFragment implements OnItemClickListener,
        FileHandler.OnFileListGetListener, OnItemLongClickListener,
        FileHandler.OnFileDeleteListener, DocumentFiledSelectWidget.OnDocumentTypeSelectListener,
        DocumentOperatorPanel.OnFileOperateListener, FileSortDialog.OnSortListener,
        FileHandler.OnFileMoveListener, IDataCallBack {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.file_operate_panel)
    DocumentOperatorPanel operatorPanel;
    @BindView(R.id.file_move_layout)
    View fileMoveView;
    @BindView(R.id.file_move)
    Button fileMoveBtn;
    @BindView(R.id.file_move_cancel)
    Button fileMoveCancelBtn;

    private FileListAdapter fileListAdapter;

    private int projectId;

    private FileHandler fileHandler;

    private CreateFolderDialog createFolderDialog;
    private DocumentFiledSelectWidget documentFiledSelectWidget;
    private PopupWindow docFieldSelectPopupWindow;
    private OuterShareWidget outerShareWidget;
    private PopupWindow sharePopupWindow;
    private FileSortDialog fileSortDialog;
    private ImagePreviewWindow imagePreviewWindow;

    //是否是移动文件的状态
    private boolean isMoveMode = false;


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        projectId = TjadApplication.getInstance().getSession().getProjectId();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        fileListAdapter = new FileListAdapter(null);
        recyclerView.setAdapter(fileListAdapter);
        fileListAdapter.setOnItemClickListener(this);
        fileListAdapter.setOnItemLongClickListener(this);
        operatorPanel.setOnFileOperateListener(this);
        TjadHttpServer.getInstance().startServer();
        fileHandler = new FileHandler(getContext());
        documentFiledSelectWidget = new DocumentFiledSelectWidget(getContext());
        documentFiledSelectWidget.setOnDocumentTypeSelectListener(this);
        documentFiledSelectWidget.check(fileHandler.getType());
        outerShareWidget = new OuterShareWidget(getContext());
        fileHandler.requestFileList(projectId, FileHandler.ROOT_ID,this);
        EventBus.getDefault().register(this);
    }

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.document_fragment, null);
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        titleView.setCenterText("文档 ▼");
        titleView.showLeft(true);
        titleView.setLeftImage(R.drawable.icon_scan);
    }

    @Override
    public void onItemClick(View parentView, View itemView, int position) {
        if (isMoveMode) {
            FileBean fileBean = fileListAdapter.getItemData(position);
            onFileClick(fileBean);
        } if (fileListAdapter.isEditMode()) {
            fileListAdapter.toggleCheckedPosition(position);
        } else {
            FileBean fileBean = fileListAdapter.getItemData(position);
            onFileClick(fileBean);
        }
    }

    @Override
    public void onTitleClick(int which) {
        if (which == TJADTTitleView.TITLE_CENTER) {
            if (docFieldSelectPopupWindow == null) {
                docFieldSelectPopupWindow = new PopupWindow(getContext());
                docFieldSelectPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                docFieldSelectPopupWindow.setContentView(documentFiledSelectWidget);
                docFieldSelectPopupWindow.setWidth(-1);
                docFieldSelectPopupWindow.setHeight(-2);
                docFieldSelectPopupWindow.setOutsideTouchable(true);
                docFieldSelectPopupWindow.setTouchable(true);
            }
            docFieldSelectPopupWindow.showAsDropDown(titleView);
//            docFieldSelectPopupWindow.showAtLocation(titleView, Gravity.TOP, titleView.getLeft(), titleView.getBottom() + Tools.getStatusBarHeight());
        } else if (which == TJADTTitleView.TITLE_LEFT) {
            Activity activity = getActivity();
            if (activity instanceof MainActivity) {
                ((MainActivity) activity).openQrcodeScan();
            }
        }
    }

    @OnClick({R.id.file_move, R.id.file_move_cancel})
    public void onFileMovePanelClick(View view) {
        switch (view.getId()) {
            case R.id.file_move:
                moveFile();
                break;
            case R.id.file_move_cancel:
                onFileMoveStatusChanged(false);
                onEditableStatusChanged(false);
                break;
        }
    }

    private void moveFile() {
        List<Integer> ids = (List<Integer>) fileMoveBtn.getTag();
        if (ids != null) {
            fileHandler.moveFile(projectId, fileHandler.getCurrentDisplayDirectoryId(), ids, this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private boolean isProjectChanged;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProjectChangedEvent(ProjectChangedEvent event) {
        projectId = event.getProjectId();
        //如果当前页面可见， 直接刷新， 否则， 做个标记位， 等可见时刷新
        if (isVisible()) {
            fileHandler.requestFileList(projectId, FileHandler.ROOT_ID, this);
        } else {
            isProjectChanged = true;
        }
    }

    private void onFileClick(FileBean fileBean) {
        if (fileBean != null) {
            if (fileBean.directory) {
                //进入下一级目录
                fileHandler.requestFileList(projectId, fileBean.id,this);
            } else {
                openFile(fileBean);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && isProjectChanged) {
            isProjectChanged = false;
            fileHandler.requestFileList(projectId, FileHandler.ROOT_ID, this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isVisible()) {
            onHiddenChanged(false);
        }
    }

    //打开文件
    public void openFile(final FileBean fileBean) {
        if (fileBean == null) {
            return;
        } if (fileBean.document != null && "0".equals(fileBean.document.forgeStatus)) {
            DocumentHelper.openModelFile(getContext(), fileBean.document);
//            int id = fileBean.document.id;
//            String localFile = TjadConsts.UNZIP_DOCUMENT + "/" + fileBean.name;
//            final String sourceFile = TjadConsts.DOWNLOAD_FILE + "/" + fileBean.name + ".zip";
//            File file = new File(localFile);
//            File sourceFileZip = new File(sourceFile);
//            if (file.exists()) {
//                //本地已存在解压后的文件
//                String token = TjadApplication.getInstance().getSession().getToken();
//                String url = UrlUtils.getUrl(UrlConsts.LOCAL_DOCUMENT_PREVIEW_URL, "" + TjadHttpServer.PORT, TjadConsts.APPHTML,
//                        localFile, token, projectId + "");
//                Bundle bundle = new Bundle();
//                bundle.putString("url", url);
//                RouteUtils.toPage(getContext(), PageId.WEBVIEW, bundle);
//            } else if (sourceFileZip.exists()) {
//                //本地存在zip包, 直接解压. 解压后打开
//                Tools.showToast("正在解压, 文件将在解压完成后打开");
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            ZipUtils.unzipAndRenameFolder(sourceFile, TjadConsts.UNZIP_DOCUMENT);
//                            openFile(fileBean);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }).start();
//
//            } else {
//                viewOnlineFileWithNetStatus(fileBean);
//            }
        } else if (Tools.isImageFile(fileBean.name)) {
            if (imagePreviewWindow == null) {
                imagePreviewWindow = new ImagePreviewWindow(getContext());
            }
            List<String> urlList = new ArrayList<>();
            Observable.fromIterable(fileListAdapter.getData())
                    .filter(fileBean1 -> Tools.isImageFile(fileBean1.name))
                    .doOnNext(fileBean2 -> {
                        urlList.add(fileBean2.path);
                    }).doOnComplete(() -> {
                        int index = urlList.indexOf(fileBean.path);
                        imagePreviewWindow.setImageUrlList(urlList);
                        imagePreviewWindow.show(index);
                    }).subscribe();
        } else {
            //普通文件打开
            String localFile = TjadConsts.DOWNLOAD_FILE + "/" + fileBean.name;
            File file = new File(localFile);
            if (file.exists()) {
                FileOpenUtils.openFile(file, getActivity());
            } else {
                TjDialogFragment.Builder dialog = new TjDialogFragment.Builder(getContext());
                dialog.setTitle("提示")
                        .setMessage("该文件还没有下载，是否立即下载?")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("下载", new OnDialogClickListener() {
                            @Override
                            public boolean onClick(Dialog dialog, int which) {
                                downloadFile(fileBean);
                                return true;
                            }
                        })
                        .create()
                        .show(getChildFragmentManager(), "downloadConfirm");
            }
        }
    }

    private void viewOnlineFileWithNetStatus(final FileBean fileBean) {
        if (!NetworkUtils.isNetworkConnected(getContext())) {
            Tools.showToast("网络连接失败, 请检查网络!");
            return;
        }
        if (!NetworkUtils.isWifi(getContext())) {
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
            builder.setTitle("提示")
                    .setMessage("您当前为非WIFI网络, 是否继续?")
                    .setPositiveButton("继续", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialog, int which) {
                            viewOnlineFile(fileBean);
                            return true;
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show(getChildFragmentManager(), "viewOnlineFile");
        } else {
            viewOnlineFile(fileBean);
        }
    }

    //预览在线文件
    private void viewOnlineFile(FileBean fileBean) {
        if (fileBean == null) {
            return;
        }
        if (fileBean.document != null && "0".equals(fileBean.document.forgeStatus)) {
            String localPath = TjadConsts.APPHTML;
            int id = fileBean.document.id;
            String token = TjadApplication.getInstance().getSession().getToken();
            String url = UrlUtils.getUrl(UrlConsts.REMOTE_DOCUMENT_PREVIEW_URL, "" + TjadHttpServer.PORT, localPath,
                    String.valueOf(projectId), token, String.valueOf(id));
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            RouteUtils.toPage(getContext(), PageId.WEBVIEW, bundle);
        }
    }

    private void downloadFiles(List<FileBean> fileList) {
        if (fileList != null && !fileList.isEmpty()) {
            for(FileBean file: fileList) {
                downloadFile(file);
            }
        }
    }

    private void downloadFile(final FileBean fileBean) {
        if (fileBean.document != null && "0".equals(fileBean.document.forgeStatus)) {
            int id = fileBean.document.id;
            final String localFile = TjadConsts.UNZIP_DOCUMENT + "/" + fileBean.name;
            final String sourceFile = TjadConsts.DOWNLOAD_FILE + "/" + fileBean.name + ".zip";
            final File file = new File(localFile);
            if (file.exists()) {
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                builder.setTitle("下载文件")
                        .setMessage("文件" + fileBean.name + "已存在,是否要重新下载?")
                        .setNegativeButton("取消",  null)
                        .setPositiveButton("确认", new OnDialogClickListener() {
                            @Override
                            public boolean onClick(Dialog dialog, int which) {
                                FileHelper.deleteFile(localFile);
                                FileHelper.deleteFile(sourceFile);
                                downloadFile(fileBean);
                                return true;
                            }
                        })
                .create().show(getChildFragmentManager(), "downloadFile");
            }  else {
//                Tools.showToast("已添加到下载列表...");
                File f = new File(sourceFile);
                if (f.exists()) {
                    f.delete();
                }
                String url = UrlUtils.getUrl(UrlConsts.DOCUMENT_DOWNLOAD_URL, String.valueOf(id));
                fileHandler.downloadFileWithCheck(getContext(), url, fileBean.name + ".zip", downloadListener);
            }
        } else {
            final String url = fileBean.path;
            if (!TextUtils.isEmpty(url)) {
                if (DownloadManager.getInstance().isTaskExists(url, url)) {
                    Tools.showToast("文件已经在下载中");
                } else {
                    File file = new File(TjadConsts.DOWNLOAD_FILE + "/" +fileBean.name);
                    if (file.exists()) {
                        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                        builder.setTitle("提示")
                                .setMessage("文件" + fileBean.name + "已经下载过了，是否要删除已下载文件并重新下载？")
                                .setNegativeButton("取消", null)
                                .setPositiveButton("确认", new OnDialogClickListener() {
                                    @Override
                                    public boolean onClick(Dialog dialog, int i) {
                                        fileHandler.downloadFileWithCheck(getContext(), url, fileBean.name, downloadListener);
                                        return true;
                                    }
                                })
                                .create()
                                .show(getChildFragmentManager(), "redownload");
                    } else {
                        fileHandler.downloadFileWithCheck(getContext(), url, fileBean.name, downloadListener);
                    }
                }
            }
        }
    }

    private FileHandler.OnFileDownloadListener downloadListener = new FileHandler.OnFileDownloadListener() {
        @Override
        public void onProgress(FileDownloadInfo fileDownloadInfo, long totalSize, long currSize, int progress) {
            Log.d("tjad", "下载文件: total : " + totalSize + ", current = " + currSize + ", progress = " + progress);
        }

        @Override
        public void onSuccess(FileDownloadInfo fileDownloadInfo) {
            if (fileDownloadInfo.getOutFile().getName().endsWith(".zip")) {
                try {
                    ZipUtils.unzipAndRenameFolder(fileDownloadInfo.getOutFile().getPath(), TjadConsts.UNZIP_DOCUMENT);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Log.d("tjad", "file download successs! file path = " + fileDownloadInfo.getOutFile().getPath());
        }

        @Override
        public void onFailed(FileDownloadInfo fileDownloadInfo, int errorType, String errorMsg) {
            String fileName = "";
            if (fileDownloadInfo.getOutFile() != null) {
                fileName = fileDownloadInfo.getOutFile().getName();
            }
            Tools.showToast("文件" + fileName + "下载失败");
            Log.d("tjad", "file download failed, errorType:" + errorType + "errorMsg:" + errorMsg);
        }
    };

    @OnClick({R.id.create_folder, R.id.upload_file, R.id.transfer_list, R.id.sort})
    public void onButtonClick(View view) {
        switch (view.getId()) {
            case R.id.create_folder:
                createFolder();
                break;
            case R.id.upload_file:
                checkPermissionAndPickFile();
                break;
            case R.id.transfer_list:
                RouteUtils.toPage(getContext(), PageId.FILE_TRANSFER, null);
                break;
            case R.id.sort:
                if (fileSortDialog == null) {
                    fileSortDialog = new FileSortDialog(getContext());
                    fileSortDialog.setSortBy(FileSort.SORT_BY_NAME);
                    fileSortDialog.setOnSortListener(this);
                }
                fileSortDialog.showAsDropDown(view);
                break;

        }
    }

    private void createFolder() {
        if (createFolderDialog == null) {
            createFolderDialog = new CreateFolderDialog();
            createFolderDialog.setOnConfirmListener(new CreateFolderDialog.OnConfirmListener() {
                @Override
                public void onConfirm(String text) {
                    fileHandler.createFolder(projectId, text, fileHandler.getType() == 1, fileHandler.getCurrentDisplayDirectoryId(), new FileHandler.OnCreateFolderListener() {
                        @Override
                        public void onCreateFolderFinished(boolean success, String message) {
                            if (success) {
                                Tools.showSnackBar(recyclerView, "文件夹创建成功!");
                                fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), DocumentFragment.this);
                            } else {
                                Tools.showSnackBar(recyclerView, message);
                            }
                        }
                    });
                }
            });
        }
        createFolderDialog.show(getChildFragmentManager(), "createFolder");
    }

    private void checkPermissionAndPickFile() {
        List<String> permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        if (EasyPermissions.hasPermissions(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            pickFile();
        } else if (EasyPermissions.somePermissionPermanentlyDenied(getActivity(), permissionList)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("权限已关闭")
                    .setRationale("" + "您已关闭了文件读取权限，必须要打开该权限才能使用该功能，是否前往打开？")
                    .build().show();
        } else {
            EasyPermissions.requestPermissions(
                    new PermissionRequest.Builder(this, 1001, Manifest.permission.READ_EXTERNAL_STORAGE)
                    .build()
            );
        }
    }


    private void pickFile() {
        FilePicker filePicker = new FilePicker(getActivity(), FilePicker.FILE);
        filePicker.setRootPath(Environment.getExternalStorageDirectory().getPath());
        filePicker.setOnFilePickListener(new FilePicker.OnFilePickListener() {
            @Override
            public void onFilePicked(String currentPath) {
                Tools.showToast("正在上传文件...");
                Log.d("tjad", "pick file : " + currentPath);
                fileHandler.uploadFile(projectId, fileHandler.getType() == 1, fileHandler.getCurrentDisplayDirectoryId(), currentPath, new FileHandler.OnFileUploadListener() {
                    @Override
                    public void onProgress(long totalSize, long currSize, int progress) {
                        Log.d("tjad", "onProgress total: " + totalSize + ", curreSize = " + currSize + ", progress = " + progress);
                    }

                    @Override
                    public void onSuccess(FileUploadInfo fileUploadInfo) {
                        Tools.showToast("文件上传成功！");
                        fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), DocumentFragment.this);
                        Log.d("tjad", "onSuccess: " + fileUploadInfo.getId());
                    }

                    @Override
                    public void onFailed(FileUploadInfo fileUploadInfo, int errorType, String errorMsg) {
                        Tools.showToast("文件上传失败");
                        Log.d("tjad", "onFailed. " + fileUploadInfo.getId() + ", errorType = " + errorType + ", errorMessage = " + errorMsg);
                    }
                });
            }
        });
        filePicker.show();
    }

    @Override
    public void onFileListGet(List<FileBean> fileList) {
        List<Integer> ids = (List<Integer>) fileMoveBtn.getTag();
        if (ids != null && ids.size() > 0 &&
                fileList != null && fileList.size() > 0) {
            Iterator<FileBean> iterator = fileList.iterator();
            while (iterator.hasNext()) {
                FileBean file = iterator.next();
                if (ids.contains(file.id)) {
                    iterator.remove();
                }
            }
        }
        fileListAdapter.updateData(fileList);
        fileListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onFileListFailed(String message) {
        Tools.showToast(message);
    }

    @Override
    public boolean interceptBackPressed() {
        if (sharePopupWindow != null && sharePopupWindow.isShowing()) {
            sharePopupWindow.dismiss();
            return true;
        }
        if (isMoveMode) {
            if (!fileHandler.isShowRoot()) {
                fileHandler.backToParent(projectId, this);
                return true;
            } else {
                onFileMoveStatusChanged(false);
                onEditableStatusChanged(false);
                return true;
            }
        } else if (fileListAdapter.isEditMode()) {
            onEditableStatusChanged(false);
            return true;
        } else {
            if (!fileHandler.isShowRoot()) {
                fileHandler.backToParent(projectId, this);
                return true;
            } else {
                return false;
            }
        }
    }

    @AfterPermissionGranted(1001)
    public void onPermissionFinished() {
        List<String> permissions = new ArrayList<>();
        permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        if (EasyPermissions.hasPermissions(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            pickFile();
        } else if (EasyPermissions.somePermissionPermanentlyDenied(this, permissions)){
            Tools.showToast("您拒绝了该权限，可能引起APP无法正常使用，如果需要，请去设置中打开");
        } else {
            checkPermissionAndPickFile();
        }
    }

    @Override
    public boolean onItemLongClick(View parentView, View itemView, int position) {
        FileBean fileBean = fileListAdapter.getItemData(position);
        if (!fileListAdapter.isEditMode() && !isMoveMode) {
            onEditableStatusChanged(true);
            fileListAdapter.checkPosition(position);

            operatorPanel.showPanelFor(fileBean);
        }
        return true;
    }

//    @Override
//    public void onFileHandleClick(final FileBean fileBean, int handleId) {
//        switch (handleId) {
//            case 1: //打开
//                onFileClick(fileBean);
//                break;
//            case 2://进入
//                onFileClick(fileBean);
//                break;
//            case 3://下载
//                openFile(fileBean);
//                break;
//            case 4: // 删除
//                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
//                if (fileBean.directory) {
//                    builder.setTitle("删除文件夹");
//                    builder.setMessage("删除文件夹会删除该文件夹下面的所有文件，是否确认删除？");
//                } else {
//                    builder.setTitle("删除文件");
//                    builder.setMessage("是否确认删除文件？");
//                }
//                builder.setNegativeButton("取消", null);
//                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        List<Integer> ids = new ArrayList<>();
//                        ids.add(fileBean.id);
//                        fileHandler.deleteFile(projectId, ids, new FileHandler.OnFileDeleteListener() {
//                            @Override
//                            public void onFileDelete(boolean success, String message) {
//                                if (success) {
//                                    Tools.showSnackBar(getView(), "删除成功");
//                                    fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), DocumentFragment.this);
//                                } else {
//                                    Tools.showSnackBar(getView(), message);
//                                }
//                            }
//                        });
//                    }
//                });
//                builder.show();
//                break;
//            case 5://重命名
//                FileRenameDialog dialog = new FileRenameDialog();
//                dialog.setOriginName(fileBean.name);
//                dialog.setOnConfirmListener(new FileRenameDialog.OnConfirmListener() {
//                    @Override
//                    public void onConfirm(String text) {
//                        fileHandler.renameFile(projectId, fileBean.id, text, new FileHandler.OnFileRenameListener() {
//                            @Override
//                            public void onFileRename(boolean success, String message) {
//                                if (success) {
//                                    Tools.showSnackBar(getView(), "重命名成功");
//                                    fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), DocumentFragment.this);
//                                } else {
//                                    Tools.showSnackBar(getView(), message);
//                                }
//                            }
//                        });
//                    }
//                });
//                dialog.show(getChildFragmentManager(), "renameFile");
//                break;
//            case 6: //移动
//
//                break;
//
//
//        }
//    }

    @Override
    public void onFileDelete(boolean success, String message) {
        if (success) {
            Tools.showSnackBar(getView(), "删除成功");
        } else {
            Tools.showSnackBar(getView(), message);
        }
        onEditableStatusChanged(false);
        fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), this);
    }

    @Override
    public void onDocumentTypeSelect(int type) {
        if (fileListAdapter.isEditMode()) {
            onEditableStatusChanged(false);
        }
        if (isMoveMode) {
            onFileMoveStatusChanged(false);
        }
        fileHandler.setType(type);
        operatorPanel.setType(type);
        fileHandler.requestFileList(projectId, FileHandler.ROOT_ID, this);
        if (docFieldSelectPopupWindow != null) {
            docFieldSelectPopupWindow.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFileCheckedChanged(FileCheckedChangeEvent event) {
        if (!isMoveMode) {
            List<FileBean> files = getSelectedFiles();
            if (files == null || files.size() == 0) {
                operatorPanel.setVisibility(View.GONE);
            } else {
                operatorPanel.showPanelFor(files);
            }
        }
    }

    @Override
    public boolean onFileOperate(int id) {
        final List<FileBean> files = getSelectedFiles();
        if (files.size() == 0) {
            return true;
        }
        boolean result = false;
        switch (id) {
            case DocumentOperatorPanel.OP_VIEW:
            case DocumentOperatorPanel.OP_OPEN:
                onFileClick(files.get(0));
                result = true;
                break;
            case DocumentOperatorPanel.OP_DOWNLOAD:
                downloadFiles(files);
                result = false;
                break;
            case DocumentOperatorPanel.OP_OPEN_ONLINE:
                viewOnlineFileWithNetStatus(files.get(0));
                break;
            case DocumentOperatorPanel.OP_DELETE:
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                builder.setTitle("删除文件");
                builder.setMessage("是否确认删除选中的文件？");

                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确认", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int which) {
                        List<Integer> ids = new ArrayList<>();
                        for (int i = 0; i < files.size(); i++) {
                            ids.add(files.get(i).id);
                        }
                        fileHandler.deleteFile(projectId, ids, new FileHandler.OnFileDeleteListener() {
                            @Override
                            public void onFileDelete(boolean success, String message) {
                                if (success) {
                                    Tools.showSnackBar(getView(), "删除成功");
                                    fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), DocumentFragment.this);
                                } else {
                                    Tools.showSnackBar(getView(), message);
                                }
                                operatorPanel.setVisibility(View.GONE);
                            }
                        });
                        return true;
                    }
                }).create().show(getChildFragmentManager(), "deleteFile");
                break;
            case DocumentOperatorPanel.OP_RENAME:
                FileRenameDialog dialog = new FileRenameDialog();
                dialog.setOriginName(files.get(0).name);
                dialog.setOnConfirmListener(new FileRenameDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm(String text) {
                        fileHandler.renameFile(projectId, files.get(0).id, text, new FileHandler.OnFileRenameListener() {
                            @Override
                            public void onFileRename(boolean success, String message) {
                                if (success) {
                                    Tools.showSnackBar(getView(), "重命名成功");
                                    operatorPanel.setVisibility(View.GONE);
                                    fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), DocumentFragment.this);
                                } else {
                                    Tools.showSnackBar(getView(), message);
                                }
                            }
                        });
                    }
                });
                dialog.show(getChildFragmentManager(), "renameFile");
                break;
            case DocumentOperatorPanel.OP_MOVE:
                onFileMoveStatusChanged(true);
                operatorPanel.setVisibility(View.GONE);
                List<FileBean> selectFiles = getSelectedFiles();
                List<Integer> ids = new ArrayList<>();
                for (FileBean file: selectFiles) {
                    ids.add(file.id);
                }
                fileMoveBtn.setTag(ids);
                onEditableStatusChanged(false);
                break;
            case DocumentOperatorPanel.OP_SHARE:
                shareFor(files);
                break;
            case DocumentOperatorPanel.OP_SET_LINK:
                FileBean file = files.get(0);
                Bundle bundle = new Bundle();
                bundle.putSerializable(Keys.FILE, file);
                RouteUtils.toPage(getContext(), PageId.DOC_LINK, bundle);
                break;
            case DocumentOperatorPanel.OP_PERMISSION:
                FileBean file1 = files.get(0);
                Bundle bundle1 = new Bundle();
                bundle1.putSerializable(Keys.FILE, file1);
                RouteUtils.toPage(getContext(), PageId.DOC_PERMISSION, bundle1);
                break;
            case DocumentOperatorPanel.OP_HOSTORY:
                FileBean fileBean = files.get(0);
                Bundle bundle2 = new Bundle();
                bundle2.putString(Keys.TITLE, fileBean.name);
                bundle2.putInt(Keys.FILE_ID, fileBean.id);
                RouteUtils.toFragmentActivity(getContext(), PageId.DOC_HISTORY, bundle2);
                break;
        }
        return result;
    }

    private List<FileBean> getSelectedFiles() {
        return fileListAdapter.getSelectedFileList();
    }

    private void onEditableStatusChanged(boolean editable) {
        fileListAdapter.setIsEditMode(editable);
        if (!editable) {
            fileListAdapter.clearSelectedFiles();
            operatorPanel.setVisibility(View.GONE);
        }
        fileListAdapter.notifyDataSetChanged();
    }

    private void onFileMoveStatusChanged(boolean isMoveMode) {
        this.isMoveMode = isMoveMode;
        if (isMoveMode) {
            fileMoveView.setVisibility(View.VISIBLE);
            fileHandler.requestFolder(projectId, fileHandler.getCurrentDisplayDirectoryId(), this);
        } else {
            fileMoveBtn.setTag(null);
            fileMoveView.setVisibility(View.GONE);
            fileHandler.requestFileList(projectId, fileHandler.getCurrentDisplayDirectoryId(), this);
        }
    }

    @Override
    public void onSort(int sortBy, int order) {
        List<FileBean> data = fileListAdapter.getData();
        if (data != null && data.size() > 1) {
            FileSort.sortBy(data, sortBy, order);
            fileListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onFileMove(boolean success, String message) {
        if (success) {
            Tools.showToast("文件移动成功!");
            onFileMoveStatusChanged(false);
            onEditableStatusChanged(false);
            fileMoveBtn.setTag(null);
        } else {
            Tools.showToast(message);
        }
    }

    private void shareFor(final List<FileBean> fileList) {
        if (fileList == null || fileList.size() == 0) {
            return;
        }
        if (fileList.size() == 1 && fileList.get(0).document != null) {
            //可以内部和外部分享
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
            builder.setTitle("请选择")
                    .setMessage("内部分享：分享到公司部门其他人员\n外部分享：通过QQ、微信等方式分享")
                    .setPositiveButton("内部分享", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
                            RouteUtils.toPageForResult(getActivity(), PageId.USER_SELECT, null, 1003);
                            return true;
                        }
                    })
                    .setNegativeButton("外部分享", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialog, int i) {
                            onShareOuter(fileList.get(0));
                            return true;
                        }
                    }).create().show(getChildFragmentManager(), "share");
        } else {
            //只可以内部分享
            RouteUtils.toPageForResult(getActivity(), PageId.USER_SELECT, null, 1003);
        }
    }

    private void onShareOuter(FileBean file) {
        outerShareWidget.setFileBean(file);
        if (sharePopupWindow == null) {
            sharePopupWindow = new TJPopupWindow(getActivity());
            sharePopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
            sharePopupWindow.setContentView(outerShareWidget);
            sharePopupWindow.setWidth(-1);
            sharePopupWindow.setHeight(-2);
            sharePopupWindow.setOutsideTouchable(true);
            sharePopupWindow.setTouchable(true);
            sharePopupWindow.setFocusable(true);
        }
        sharePopupWindow.showAtLocation(operatorPanel, Gravity.BOTTOM, titleView.getLeft(), titleView.getTop());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1003 && resultCode == Activity.RESULT_OK) {
            final List<Serializable> selects = (List<Serializable>) data.getSerializableExtra(Keys.SELECTED_RESULTS);
            if (selects != null && selects.size() > 0) {
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                builder.setTitle("提示")
                        .setMessage("确定要分享该文件给所选择人员吗？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new OnDialogClickListener() {
                            @Override
                            public boolean onClick(Dialog dialog, int i) {
                                List<FileBean> selectedFiles = getSelectedFiles();
                                List<Serializable> selectf = new ArrayList<>();
                                selectf.addAll(selectedFiles);
                                RemoteDataService.shareDocuments(projectId, Tools.getIds(selectf),
                                        Tools.getIds(selects), DocumentFragment.this);
                                return true;
                            }
                        }).show(getFragmentManager());
            }
        }
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (httpId == HttpId.DOC_SHARE) {
            if (!TextUtils.isEmpty(errorMsg)) {
                Tools.showToast(errorMsg);
            } else {
                Tools.showToast("分享失败");
            }
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        if (httpId == HttpId.DOC_SHARE) {
            CommonBean<BaseBean> bean = (CommonBean<BaseBean>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                builder.setTitle("提示")
                        .setMessage("分享成功！")
                        .setPositiveButton("确定", null)
                        .show(getFragmentManager());
            } else {
                Tools.showToast(bean.respMsg);
            }
        }
    }
}
